package com.dftc.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;


import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

/**
 * @author SZQ
 * @test
 * @version
 * @创建时间：2016年2月24日 上午9:41:03
 * @类说明 模拟http请求
 */
public class HttpSimulation {
	private static String mac = "";
	private static final String device_id = "123456d1d2";
	// private static String loginUrl = "http://test.auth.zpdteck.com/login";
	private static String loginUrl = "http://test.auth.zpdteck.com:8550/login";
	private static String loginStr = "sn=" + device_id
			+ "&gwip=192.168.118.1&umac=38:bc:1a:b3:b2:a6&redirect_url=http://test.site.zpdteck.com/0/default/index.html&appendix&_=1456132775827";
	// private static String logonUrl = "http://test.auth.zpdteck.com/auth";
	private static String logonUrl = "http://test.auth.zpdteck.com:8550/auth";

	private static final String gateway_mac = "aa:bb:cc:dd:ee:ff";
	private static Logger log = Logger.getLogger(HttpSimulation.class);

	public static void main(String[] args) {
		for (int i = 0; i < 1; i++) {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						System.out.println("ThreadName :  " + Thread.currentThread().getName());
						simulationLogin();
//						try {
//							Thread.sleep(1000);
//						} catch (InterruptedException e1) {
//							e1.printStackTrace();
//						}
						simulationLogon();
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}

			}).start();
		}

		// 测试执行一次
		/*
		 * simulationLogin(); try { Thread.sleep(100); } catch
		 * (InterruptedException e1) { e1.printStackTrace(); }
		 * simulationLogon();
		 */
	}

	/**
	 * @Description: TODO(随机生成mac)
	 * @author SZQ
	 * @date 2016年2月24日 上午9:51:08
	 * @version V1.0
	 * @return
	 */
	public static String getMac() {
		// ubuntu终端下获取mac命令
		String command = "(dd if=/dev/urandom bs=512 count=1 2>/dev/null | md5sum | sed 's/^\\(..\\)\\(..\\)\\(..\\).*$/\\1:\\2:\\3/')";
		String mac = "52:54:00:";
		String[] CMDS = new String[3];
		CMDS[0] = "/bin/sh";
		CMDS[1] = "-c";
		CMDS[2] = command;
		Runtime runtime = Runtime.getRuntime();
		try {
			Process pro = runtime.exec(CMDS);
			InputStreamReader reader = new InputStreamReader(pro.getInputStream());
			BufferedReader buff = new BufferedReader(reader);
			StringBuffer sb = new StringBuffer();
			String line = null;
			while ((line = buff.readLine()) != null) {
				sb.append(line);
			}
			mac += sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mac;
	}

	/**
	 * @Description: TODO(java 模拟HTTP POST 请求)
	 * @author SZQ
	 * @date 2016年2月24日 上午9:51:08
	 * @version V1.0
	 * @return
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @Description: TODO(java 模拟HTTP Get 请求)
	 * @author SZQ
	 * @date 2016年2月24日 上午9:51:08
	 * @version V1.0
	 * @return
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);

			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @Description: TODO(用一句话描述该文件做什么)
	 * @author SZQ
	 * @date 2016年2月24日 上午9:43:37
	 * @version V1.0
	 */
	public static void simulationLogin() {
		System.out.println("login : " + new Date() + " " + "login" + loginUrl + loginStr);
		String retStr = sendGet(loginUrl, loginStr);
		System.out.println("login return " + new Date() + " " + retStr);
	}

	/**
	 * @Description: TODO(用一句话描述该文件做什么)
	 * @author SZQ
	 * @date 2016年2月24日 上午9:59:13
	 * @version V1.0 para: { "auth_type": 2, "client_ip": "192.168.118.222",
	 *          "client_mac": "38:bc:1a:b3:b2:a6", "device_id": "861B5E827F90",
	 *          "device_vendor": "ZOPODO", "user_para":
	 *          "token=token&redirect_url=http://test.site.zpdteck.com/0/default/index.html",
	 *          "username": "", "gateway_mac": "861B5E827F90", "online_time": 0,
	 *          "upflow": 0, "downflow": 0 }
	 * 
	 * 
	 * 
	 */
	public static void simulationLogon() {
		JSONObject json = new JSONObject();
		json.put("auth_type", 2);
		json.put("client_ip", "");
		json.put("client_mac", HttpSimulation.getMac());
		json.put("device_id", device_id);
		json.put("device_vendor", "device_vendor");
		json.put("user_para", "token=token&redirect_url=http://test.site.zpdteck.com/0/default/index.html");
		json.put("gateway_mac", gateway_mac);
		json.put("online_time", 0);
		json.put("upflow", 0);
		json.put("upflow", 0);

		System.out.println("logon: " + new Date() + " " + "logon" + logonUrl + " ?reqParam=  " + json);
		String retStr = sendPost(logonUrl, json.toString());
		System.out.println("logon return : " + new Date() + " " + retStr);

	}
}

class MyThread implements Runnable {
	public void run() {
		for (int j = 0; j < 1000; j++) {
			System.out.println("ThreadName :  " + Thread.currentThread().getName());
			HttpSimulation.simulationLogin();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			HttpSimulation.simulationLogon();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
